package com.bayss.core.service.deliveryman;

import com.alibaba.fastjson.JSONObject;
import com.bayss.core.DokoServerException;
import com.bayss.core.DokoServerExceptionFactor;
import com.bayss.core.entity.delivery.DeliverymanInfo;
import com.bayss.core.entity.delivery.DeliverymanInfoExample;
import com.bayss.core.entity.delivery.DeliverymanLoginInfo;
import com.bayss.core.entity.delivery.DeliverymanLoginInfoExample;
import com.bayss.core.entity.delivery.mapper.DeliverymanInfoMapper;
import com.bayss.core.entity.delivery.mapper.DeliverymanLoginInfoMapper;
import com.bayss.core.entity.order.Order;
import com.bayss.core.entity.order.OrderExample;
import com.bayss.core.entity.order.mapper.OrderMapper;
import com.bayss.core.entity.rbac.OBGUserInfo;
import com.bayss.core.entity.rbac.mapper.OBGUserInfoMapper;
import com.bayss.core.entity.station.Station;
import com.bayss.core.entity.station.mapper.StationMapper;
import com.bayss.core.enums.HandleCode;
import com.bayss.core.util.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;

/**
 * Created by yangjian on 2019/12/11.
 */
@Service
public class DeliverymanService {
    public static final Logger logger = LoggerFactory.getLogger(DeliverymanService.class);

    private final DeliverymanInfoMapper deliverymanInfoMapper;

    private final DeliverymanLoginInfoMapper deliverymanLoginInfoMapper;

    private final StationMapper stationMapper;

    private final OBGUserInfoMapper obgUserInfoMapper;

    private final OrderMapper orderMapper;

    public DeliverymanService(DeliverymanInfoMapper deliverymanInfoMapper,
                              DeliverymanLoginInfoMapper deliverymanLoginInfoMapper,
                              StationMapper stationMapper, OBGUserInfoMapper obgUserInfoMapper,
                              OrderMapper orderMapper) {
        this.deliverymanInfoMapper = deliverymanInfoMapper;
        this.deliverymanLoginInfoMapper = deliverymanLoginInfoMapper;
        this.stationMapper = stationMapper;
        this.obgUserInfoMapper = obgUserInfoMapper;
        this.orderMapper = orderMapper;
    }

    /**
     * 创建骑手
     */
    public boolean save(DeliverymanInfo deliverymanInfo){
        Station station = stationMapper.selectByPrimaryKey(deliverymanInfo.getStationId());
        if (station == null) {
            throw new DokoServerException(DokoServerExceptionFactor.DEFAULT, "配送站不存在");
        }
        OBGUserInfo obgUserInfo = obgUserInfoMapper.selectByPrimaryKey(deliverymanInfo.getOperatorId().intValue());
        if (obgUserInfo == null) {
            throw new DokoServerException(DokoServerExceptionFactor.DEFAULT, "操作人不存在");
        }
        deliverymanInfo.setStationName(station.getStationName());
        deliverymanInfo.setOperatorName(obgUserInfo.getNickname());
        return deliverymanInfoMapper.insertSelective(deliverymanInfo) > 0;
    }

    /**
     * 修改骑手
     */
    public boolean update(DeliverymanInfo deliverymanInfo){
        Station station = stationMapper.selectByPrimaryKey(deliverymanInfo.getStationId());
        if (station == null) {
            throw new DokoServerException(DokoServerExceptionFactor.DEFAULT, "配送站不存在");
        }
        OBGUserInfo obgUserInfo = obgUserInfoMapper.selectByPrimaryKey(deliverymanInfo.getOperatorId().intValue());
        if (obgUserInfo == null) {
            throw new DokoServerException(DokoServerExceptionFactor.DEFAULT, "操作人不存在");
        }
        deliverymanInfo.setOperatorName(obgUserInfo.getNickname());
        deliverymanInfo.setStationName(station.getStationName());
        return deliverymanInfoMapper.updateByPrimaryKeySelective(deliverymanInfo) > 0;
    }

    /**
     * 查询棘手
     */
    public PageInfo<DeliverymanInfo> query(Long stationId, Integer page, Integer pageSize){
        DeliverymanInfoExample deliverymanInfoExample = new DeliverymanInfoExample();
        deliverymanInfoExample.setOrderByClause("create_time desc");
        if (stationId != null && stationId != 0) {
            DeliverymanInfoExample.Criteria criteria = deliverymanInfoExample.createCriteria();
            criteria.andStationIdEqualTo(stationId);
        }
        PageInfo<DeliverymanInfo> pageInfo = PageHelper.startPage(page, pageSize).doSelectPageInfo(() -> deliverymanInfoMapper.selectByExample(deliverymanInfoExample));
        List<DeliverymanInfo> deliverymanInfos = pageInfo.getList();
        for (DeliverymanInfo deliverymanInfo : deliverymanInfos) {
            OrderExample orderExample = new OrderExample();
            OrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andHidEqualTo(deliverymanInfo.getId().intValue());
            criteria.andOrderStatusIn(Arrays.asList(HandleCode.SENDING.ordinal(), HandleCode.SENDWAIT.ordinal()));
            List<Order> orders = orderMapper.selectByExample(orderExample);
            if (CollectionUtils.isEmpty(orders)) {
                deliverymanInfo.setRunningCount(0);
            } else {
                deliverymanInfo.setRunningCount(orders.size());
            }
        }
        return pageInfo;
    }

    /**
     * 删除
     */
    public boolean del(Long id){
        return deliverymanInfoMapper.deleteByPrimaryKey(id) > 0;
    }

    public boolean updateState(Long id, int state){
        DeliverymanInfo deliverymanInfo = deliverymanInfoMapper.selectByPrimaryKey(id);
        if (deliverymanInfo == null) {
            throw new DokoServerException(DokoServerExceptionFactor.DEFAULT, "骑手不存在");
        }
        deliverymanInfo.setState(state);
        return deliverymanInfoMapper.updateByPrimaryKey(deliverymanInfo) > 0;
    }

    /**
     * 骑手打卡记录
     */
    public PageInfo<DeliverymanInfo> queryLoginInfo(Long deliverymanId, Integer page, Integer pageSize){
        DeliverymanLoginInfoExample deliverymanLoginInfoExample = new DeliverymanLoginInfoExample();
        deliverymanLoginInfoExample.setOrderByClause("time desc");
        DeliverymanLoginInfoExample.Criteria criteria = deliverymanLoginInfoExample.createCriteria();
        criteria.andDeliIdEqualTo(deliverymanId);
        PageInfo<DeliverymanInfo> pageInfo = PageHelper.startPage(page, pageSize).doSelectPageInfo(() -> deliverymanLoginInfoMapper.selectByExample(deliverymanLoginInfoExample));
        return pageInfo;
    }

    public DeliverymanInfo get(Long id){
        return deliverymanInfoMapper.selectByPrimaryKey(id);
    }

    /**
     * 骑手登录
     */
    public JSONObject login(String account, String password, String addrName){
        String token;
        DeliverymanInfo deliverymanInfo;
        DeliverymanInfoExample example = new DeliverymanInfoExample();
        DeliverymanInfoExample.Criteria criteria = example.createCriteria();
        criteria.andAccountEqualTo(account);
        criteria.andPasswordEqualTo(password);
        List<DeliverymanInfo> deliverymanInfos = deliverymanInfoMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(deliverymanInfos)) {
            deliverymanInfo = deliverymanInfos.get(0);
            token = TokenUtils.createToken("deliveryman_id", deliverymanInfo.getId().intValue(), 24);
            deliverymanInfo.setStatus(1);
            String picUrl = deliverymanInfo.getPhotoUrl();
            deliverymanInfo.setPhotoUrl(null);
            deliverymanInfoMapper.updateByPrimaryKeySelective(deliverymanInfo);
            DeliverymanLoginInfo deliverymanLoginInfo = new DeliverymanLoginInfo();
            deliverymanLoginInfo.setDeliId(deliverymanInfo.getId());
            deliverymanLoginInfo.setType(1);
            deliverymanLoginInfo.setAddrName(deliverymanInfo.getStationName());
            deliverymanLoginInfoMapper.insertSelective(deliverymanLoginInfo);
            deliverymanInfo.setPhotoUrl(picUrl);
        } else {
            throw new DokoServerException(DokoServerExceptionFactor.DEFAULT, "登录名或密码错误");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", token);
        jsonObject.put("deliverymanInfo", deliverymanInfo);
        return jsonObject;
    }

    /**
     * 骑手登出
     */
    public boolean outlogin(Long id, String addrName){
        DeliverymanInfo deliverymanInfo = deliverymanInfoMapper.selectByPrimaryKey(id);
        deliverymanInfo.setStatus(0);
        deliverymanInfoMapper.updateByPrimaryKey(deliverymanInfo);
        DeliverymanLoginInfo deliverymanLoginInfo = new DeliverymanLoginInfo();
        deliverymanLoginInfo.setDeliId(id);
        deliverymanLoginInfo.setAddrName(deliverymanInfo.getStationName());
        deliverymanLoginInfo.setType(2);
        deliverymanLoginInfoMapper.insertSelective(deliverymanLoginInfo);
        return true;
    }

}
